package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Component
// 生成唯一id
public class RedisIdWorker {


    private StringRedisTemplate stringRedisTemplate;

    private static  final int COUNT_BITS =32;
    private static final long BEGIN_TIME_STAMP = 1667835617L;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public Long nextId(String keyPrefix){
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSeconds = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSeconds-BEGIN_TIME_STAMP;

        // 生成序列
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:mm:dd"));
        // 最终在redis中记录的 count的值
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
//        System.out.println(count);
//        log.info("{}",count);


        return timeStamp << COUNT_BITS | count;
    }


}
